package com.woniuxy.yygh.common.helper;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: JWT 工具类
 * <P> Date: 2022/3/3:19:23
 * <P> Description:
 */

public class JwtHelper {
    // 过期时间
    private static long tokenExpiration = 24*60*60*1000;
    private static String tokenSignKey = "123456";

    /**
        * TODO: 根据参数生成token 用户id和用户名
    **/
    public static String createToken(Long userId, String userName) {
        String token = Jwts.builder()
                .setSubject("YYGH-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .claim("userName", userName)
                .signWith(SignatureAlgorithm.HS256, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)//设置数据压缩格式
                .compact();
        return token;
    }

    /**
        * TODO:从token获得用户id
    **/
    public static Long getUserId(String token) {
        if(StringUtils.isEmpty(token)) {
            return null;
        }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = (Integer)claims.get("userId");
        return userId.longValue();
    }
    
    /**
        * TODO:从token获得用户id
    **/
    public static String getUserName(String token) {
        if(StringUtils.isEmpty(token)) {
            return "";
        }
        Jws<Claims> claimsJws
                = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("userName");
    }

}
